//
//  DetailMusicViewController.swift
//  FirstSwiftProduct
//
//  Created by 知合金服-Mini on 2017/12/19.
//  Copyright © 2017年 范泽华. All rights reserved.
//

import UIKit
import Speech
//import


/**
 SFSpeechRecognizer：这个类是语音识别的操作类，用于语音识别用户权限的申请，语言环境的设置，语音模式的设置以及向Apple服务发送语音识别的请求。
 
 SFSpeechRecognitionTask：这个类是语音识别服务请求任务类，每一个语音识别请求都可以抽象为一个SFSpeechRecognitionTask实例，其中SFSpeechRecognitionTaskDelegate协议中约定了许多请求任务过程中的监听方法。
 
 SFSpeechRecognitionRequest:语音识别请求类，需要通过其子类来进行实例化。
 
 SFSpeechURLRecognitionRequest：通过音频URL来创建语音识别请求。
 
 SFSpeechAudioBufferRecognitionRequest:通过音频流来创建语音识别请求。
 
 SFSpeechRecognitionResult：语音识别请求结果类。
 
 SFTranscription：语音转换后的信息类。
 
 SFTranscriptionSegment：语音转换中的音频节点类。
 
 //获取当前用户权限状态+ (SFSpeechRecognizerAuthorizationStatus)authorizationStatus;
 //申请语音识别用户权限+ (void)requestAuthorization:(void(^)(SFSpeechRecognizerAuthorizationStatus status))handler;
 //获取所支持的所有语言环境+ (NSSet *)supportedLocales;
 //初始化方法 需要注意 这个初始化方法将默认以设备当前的语言环境作为语音识别的语言环境- (nullable instancetype)init;
 //初始化方法 设置一个特定的语言环境- (nullable instancetype)initWithLocale:(NSLocale *)locale NS_DESIGNATED_INITIALIZER;
 //语音识别是否可用@property (nonatomic, readonly, getter=isAvailable) BOOL available;//语音识别操作类协议代理@property (nonatomic, weak) id delegate;
 //设置语音识别的配置参数 需要注意 在每个语音识别请求中也有这样一个属性 这里设置将作为默认值
 //如果SFSpeechRecognitionRequest对象中也进行了设置 则会覆盖这里的值
 /* typedef NS_ENUM(NSInteger, SFSpeechRecognitionTaskHint) {
 SFSpeechRecognitionTaskHintUnspecified = 0,
 // 无定义               SFSpeechRecognitionTaskHintDictation = 1,
 // 正常的听写风格               SFSpeechRecognitionTaskHintSearch = 2,
 // 搜索风格               SFSpeechRecognitionTaskHintConfirmation = 3,
 // 短语风格 }; */@property (nonatomic) SFSpeechRecognitionTaskHint defaultTaskHint;
 //使用回调Block的方式进行语音识别请求 请求结果会在Block中传入- (SFSpeechRecognitionTask *)recognitionTaskWithRequest:(SFSpeechRecognitionRequest *)request    resultHandler:(void (^)(SFSpeechRecognitionResult * __nullable result, NSError * __nullable error))resultHandler;
 //使用代理回调的方式进行语音识别请求
 - (SFSpeechRecognitionTask *)recognitionTaskWithRequest:(SFSpeechRecognitionRequest *)request    delegate:(id )delegate;//设置请求所占用的任务队列
 
 */


class DetailMusicViewController: BasePushViewController ,SFSpeechRecognitionTaskDelegate ,SFSpeechRecognizerDelegate{
    
    
    //SFSpeechRecognizerDelegate
    //当语音识别操作可用性发生改变时会被调用
    func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
        
    }
    //SFSpeechRecognitionTaskDelegate
    // Called when the task first detects speech in the source audio
    //当开始检测音频源中的语音时首先调用此方法
    func speechRecognitionDidDetectSpeech(_ task: SFSpeechRecognitionTask) {
        
    }
    
    
    //
    func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishRecognition recognitionResult: SFSpeechRecognitionResult) {
        print(recognitionResult.bestTranscription.formattedString)
    }
    
    func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) {
        print("识别完毕")
    }
    
    func speechRecognitionTaskWasCancelled(_ task: SFSpeechRecognitionTask) {
        print("取消取消取消取消")
    }
    
    var recognitionTask : SFSpeechRecognitionTask!
    
    var speechRecognizer : SFSpeechRecognizer! // 语音识别器
    
    var request:SFSpeechURLRecognitionRequest!
    
    var speechRequest:SFSpeechAudioBufferRecognitionRequest! // 语音请求对象
    
//    var audioEngine : ava
    
    @IBOutlet weak var recognitionLabel: UILabel!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        SFSpeechRecognizer.requestAuthorization { (status) in
            
            switch status {
            case SFSpeechRecognizerAuthorizationStatus.notDetermined:
                print("结果未知 用户尚未进行选择")
                break
            case .denied:
                print("用户拒绝授权语音识别")
                break
            case .restricted:
                print("设备不支持语音识别功能")
                break
            case .authorized:
                print("用户授权语音识别")
                break
            
            }
        }
    //创建语音识别操作类对象SFSpeechRecognizer * rec = [[SFSpeechRecognizer alloc]init];//通过一个音频路径创建音频识别请求
//        SFSpeechRecognitionRequest * request = [[SFSpeechURLRecognitionRequest alloc]initWithURL:[[NSBundle mainBundle] URLForResource:@"7011" withExtension:@"m4a"]];
//        //进行请求
//        [rec recognitionTaskWithRequest:request resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
//        ‍‍    //打印语音识别的结果字符串
//                NSLog(@"%@",result.bestTranscription.formattedString);
//    }];
    
    
        
        //1.创建SFSpeechRecognizer识别实例
        self.speechRecognizer = SFSpeechRecognizer.init(locale: NSLocale.init(localeIdentifier: "zh_CN") as Locale)
        
        //2.创建识别请求
        let path = Bundle.main.path(forResource: "1122334455.mp3", ofType: nil)
        
        
        let url = URL.init(fileURLWithPath: path!)
        
        
        request = SFSpeechURLRecognitionRequest.init(url: url)
        
        
        //3.开始识别任务
        self.recognitionTask = self.speechRecognizer.recognitionTask(with: request, resultHandler: { (rrrequest, error) in


            print("正确",rrrequest?.bestTranscription.formattedString as Any,"结束没",rrrequest?.isFinal as Any)

                print("错误",error as Any)

            switch self.recognitionTask.state{
                case .running:
                    print("running")
                
                case .starting:
                    print("stating")
                
                case .finishing:
                    print("finish")
                        break
                case .completed:
                    print("completed")
                        break
                case .canceling:
                    print("canceling")
                        break
            }
            

        })
        
//       self.recognitionTask = self.speechRecognizer.recognitionTask(with: request, delegate: self)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func ButtonTouchBegin(_ sender: UIButton) {
        //touch
        print("begin")
    }
    @IBAction func ButtonTouchEnd(_ sender: Any) {
        //touchend
        print("end")
    }
    
    @IBAction func touchDown(_ sender: UIButton) {
        print("touchDown")
    }
    @IBAction func repeaat(_ sender: Any) {
        print("repat")
    }
    @IBAction func start(_ sender: UIButton) {
//        self.recognitionTask = self.speechRecognizer.recognitionTask(with: request, delegate: self)
        print("touchUp")
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
